package com.ruizhong.integratedmediawithoutc.util;

import javax.websocket.EncodeException;
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.text.DecimalFormat;

public class NIOFileCopyWithProgress {

    public interface ProgressCallback {
        void onProgress(double percent) throws EncodeException, IOException;
        void onComplete() throws EncodeException, IOException;
        void onError(String message);
    }

    public static void copyFile(Path source, Path dest, ProgressCallback callback) {
        if (!Files.exists(source)) {
            callback.onError("源文件不存在");
            return;
        }

        try (FileChannel inChannel = FileChannel.open(source);
             FileChannel outChannel = FileChannel.open(dest, 
                 StandardOpenOption.CREATE, 
                 StandardOpenOption.WRITE, 
                 StandardOpenOption.TRUNCATE_EXISTING)) {

            long fileSize = inChannel.size();
            long position = 0;
            long bytesCopied;
            
            while (position < fileSize) {
                bytesCopied = inChannel.transferTo(position, 8192, outChannel);
                position += bytesCopied;
                
                // 计算并回调进度
                double progress = (double) position / fileSize * 100;
                callback.onProgress(progress);
            }
            
            callback.onComplete();
            
        } catch (IOException e) {
            callback.onError("复制失败: " + e.getMessage());
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Path source = Paths.get("source.mp4");
        Path dest = Paths.get("dest.mp4");
        
        ProgressCallback callback = new ProgressCallback() {
            private final DecimalFormat df = new DecimalFormat("0.00");
            
            @Override
            public void onProgress(double percent) {
                System.out.print("\r复制进度: " + df.format(percent) + "%");
            }
            
            @Override
            public void onComplete() {
                System.out.println("\n文件复制完成!");
            }
            
            @Override
            public void onError(String message) {
                System.err.println("\n错误: " + message);
            }
        };
        
        copyFile(source, dest, callback);
    }
}